package model;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;


public class Lexica {
	
	private final Lexica lexica = new Lexica();
	private final static TextSplitter splitter = new TextSplitter("");
	private static Collection<Word> wordList = new LinkedList<Word>();

	Error NoPrecedessorError = new Error("there is no Precedessor available for the definded Position.");
	Error NoSuccessorError = new Error("there is no Successor available for the definded Position.");
	
	public Lexica getLexica() {
		return lexica;
	}
	
	private Lexica(){
		
	}
	
	public static Lexica create(final String text){
		final HashMap<String, Word> map = new HashMap<String, Word>();

		final Lexica result = new Lexica();
		wordList = Lexica.splitter.splitText(text);
		final Iterator<Word> i = wordList.iterator();
		while(i.hasNext()){
			final Word current = i.next();
			current.normalize();
			if(!(map.containsKey(current.getValue()))){
				map.put(current.getValue(), current);
			}
			map.get(current.getO()).addOccurence(current.getO());
		}
		return result;
		
	}
	
	public Collection<Word> getWordList(){
		return wordList;
	}
	
	public Word getPrecedessor(final Occurence o) throws Error{
		
		final Iterator<Word> i = this.getWordList().iterator();
		while(i.hasNext()){
			final Word current = i.next();
			
			final Iterator<Occurence> iOcc = current.getO().iterator();
			while(iOcc.hasNext()){
				final Occurence currentOcc = iOcc.next();
				if(currentOcc.getOrder() == (o.getOrder()-1)){
					return current;
				}
			}
			
		}
		throw NoPrecedessorError;
	}
	
	public Word getSuccesssor(final Occurence o) throws Error{
		
		final Iterator<Word> i = this.getWordList().iterator();
		while(i.hasNext()){
			final Word current = i.next();
			
			final Iterator<Occurence> iOcc = current.getO().iterator();
			while(iOcc.hasNext()){
				final Occurence currentOcc = iOcc.next();
				if(currentOcc.getOrder() == (o.getOrder()+1)){
					return current;
				}
			}
			
		}
		throw NoSuccessorError;
	}
	
	public LinkedList<Word> getSuccessors(final Word word){
		return null;
		
	}

}
